package com.stone.project.service.impl;

import com.stone.project.domain.SysRole;
import com.stone.project.domain.SysUser;
import com.stone.project.service.SysRoleService;
import com.stone.project.service.SysUserRoleService;
import com.stone.project.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author stone
 * 创建日期  2022/11/7
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUser one = sysUserService.lambdaQuery()
                .eq(SysUser::getUsername, s)
                .one();
        if (one == null)
            throw new UsernameNotFoundException("用户不存在");

        Set<SimpleGrantedAuthority> roles = sysRoleService.lambdaQuery()
                .eq(SysRole::getName, one.getUsername())
                .list()
                .stream()
                .map(e -> new SimpleGrantedAuthority(e.getName()))
                .collect(Collectors.toSet());
        User user = new User(one.getUsername(), one.getPassword(), roles);
        return user;
    }
}
